﻿using System.Text;
using System.Xml;
using LmgCMS.Model;
using LmgCMS.Service;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Swagger;

namespace LmgCMS.Areas.API.Controllers {
    /// <summary>
    /// 新闻
    /// </summary>
    [ApiExplorerSettings(GroupName = SwaggerGroupingModel.GROUPNAME_COMM)]
    public class NewsController : BaseController<News>
    {
        private readonly INewsService _newsService;
        private readonly INewsDataService _newsdataService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ISiteService _siteService;
        public NewsController(INewsService newsService, INewsDataService newsdataService, ISiteService siteService, IWebHostEnvironment webHostEnvironment)
        {
            _newsService = newsService;
            _newsdataService = newsdataService;
            _siteService = siteService;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 添加或者修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitSaveForm(NewsRequest request, bool isUpdate)
        {
            try
            {
                string newId = UUIDUtils.Fid;
                var news = DataMapper.Mapper<News, NewsRequest>(request);
                var newsdata = DataMapper.Mapper<NewsData, NewsRequest>(request);
                if (isUpdate)
                {
                    _newsService.Update(news);
                    _newsdataService.Update(newsdata);
                }
                else
                {
                    news.ID = newId;
                    newsdata.ID = newId;
                    _newsService.Add(news);
                    _newsdataService.Add(newsdata);
                }
            }
            catch (Exception ex)
            {
                return Error("提交失败：" + ex.Message);
            }
            EmailHepler.SendEmail("1640601039@qq.com", "南昌微工场科技有限公司", "发布了【" + request.Title + "】新闻");
            return Success("提交成功。");
        }
        /// <summary>
        ///  获取新闻信息
        /// </summary>
        /// <param name="ID">新闻ID</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetNewsInfo(string ID)
        {
            if (string.IsNullOrWhiteSpace(ID)) return Error("参数ID不能为空！");
            var _news = _newsService.Find(ID);
            var _newsdata = _newsdataService.Find(ID);
            var ret = new
            {
                news = _news,
                newsdata = _newsdata,
            };
            return Content(ret.ToJson());
        }
        /// <summary>
        ///   获取最新分类新闻信息
        /// </summary>
        /// <param name="category">分类名称</param>
        /// <param name="top">查询条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetNewsLast(string category, int top)
        {
            var list = _newsService.GetNewsLast(category, top);
            return Content(list.ToJson());
        }
        /// <summary>
        /// 测试数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult TestData()
        {
            for (int i = 0; i < 1111; i++)
            {
                News news = new News();
                news.ID = UUIDUtils.Fid;
                news.Category = "新闻资讯";
                news.Title = "测试新闻分页" + i;
                news.FTitle = "测试新闻分页" + i;
                news.Url = "https://www.cnblogs.com/luomingui";
                news.Author = "本站";
                _newsService.Add(news);
            }
            return Success("ok");
        }

        #region CreateSiteMap
        /// <summary>
        /// 创建站点地图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CreateSiteMap()
        {
            try
            {
                string url = HttpContext.Request.Host.Host;
                string siteName = "luomingui";
                var siteInfo = _siteService.Find(x => x.SiteUrl == url && x.Status== 1);
                if (siteInfo != null)
                {
                    siteName = siteInfo.Name;
                }
                //XML
                string currentXmlFileName = "sitemap.xml";
                string sitemapPath = _webHostEnvironment.WebRootPath;
                string sitemapFileFullNamePath = string.Format(sitemapPath + "/{0}", currentXmlFileName);

                //TXT
                string sitemaptxtname = "sitemap.txt";
                string sitemapTxTFileFullNamePath = string.Format(sitemapPath + "/{0}", sitemaptxtname);
                FileStream fs = new FileStream(sitemapTxTFileFullNamePath, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                sw.BaseStream.Seek(0, SeekOrigin.End);
                sw.WriteLine(url);
                //html
                string sitemaphtmlname = "sitemap.html";
                string sitemapHtmlFileFullNamePath = string.Format(sitemapPath + "/{0}", sitemaphtmlname);
                FileStream htmlfs = new FileStream(sitemapHtmlFileFullNamePath, FileMode.Create, FileAccess.Write);
                StreamWriter htmlsw = new StreamWriter(htmlfs, System.Text.Encoding.UTF8);
                htmlsw.BaseStream.Seek(0, SeekOrigin.End);
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<!DOCTYPE html>");
                sb.AppendLine("<html lang='en'>");
                sb.AppendLine("<head>");
                sb.AppendLine("<meta charset='UTF-8'>");
                sb.AppendLine("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
                sb.AppendLine("<title>sitemap</title>");
                sb.AppendLine("</head>");
                sb.AppendLine("<body>");
                sb.AppendLine("<style>a{color:rgb(0, 0, 238);font-size:13px;}</style>");
                sb.AppendLine("<ol><li><a href='" + url + "'>" + siteName + "</a></li>");

                XmlDocument xmlDoc = new XmlDocument();
                //加入XML的声明段落：<?xmlversion="1.0" encoding="utf-8"?>
                XmlDeclaration xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(xmldecl);
                XmlElement xe = xmlDoc.CreateElement("urlset");//创建一个urlset根元素
                xmlDoc.AppendChild(xe);
                XmlNode root = xmlDoc.SelectSingleNode("urlset");//查找<urlset>
                XmlElement xmle = xmlDoc.CreateElement("url"); //创建一个<api>节点 
                XmlElement xmle1 = xmlDoc.CreateElement("loc");
                xmle1.InnerText = url;//此处拼接动态地址
                xmle.AppendChild(xmle1);
                XmlElement xmle2 = xmlDoc.CreateElement("lastmod");
                xmle2.InnerText = DateTime.Now.ToString6();
                xmle.AppendChild(xmle2);
                XmlElement xmle3 = xmlDoc.CreateElement("changefreq");
                xmle3.InnerText = "always";
                xmle.AppendChild(xmle3);
                XmlElement xmle4 = xmlDoc.CreateElement("priority");
                xmle4.InnerText = "1";
                xmle.AppendChild(xmle4);
                xe.AppendChild(xmle);

                var articleList = _newsService.FindAll();  //获取需要生成sitemmap的数据
                foreach (var item in articleList)
                {
                    var spriderUrl = string.Format("/News/Faq/Show/", item.ID);
                    sw.WriteLine(spriderUrl);
                    sb.AppendLine("<li><a href='" + spriderUrl + "'>" + item.Title + "</a></li>");

                    XmlElement xe1 = xmlDoc.CreateElement("url"); //创建一个<api>节点 
                    XmlElement xesub1 = xmlDoc.CreateElement("loc");
                    xesub1.InnerText = spriderUrl;//此处拼接动态地址
                    xe1.AppendChild(xesub1);
                    XmlElement xesub2 = xmlDoc.CreateElement("lastmod");
                    xesub2.InnerText = item.AddTime.ToString("yyyy-MM-dd");
                    xe1.AppendChild(xesub2);
                    //是用来告诉搜索引擎网站更新的周期，描述的单词：always（经常）、hourly（每时）、daily（每天）、weekly（每周）、monthly（每月）、yearly（每年）。
                    //像首页就可以用“always”；对于很久前的链接或不再更新内容的链接就可以使用“yearly”。
                    XmlElement xesub3 = xmlDoc.CreateElement("changefreq");
                    xesub3.InnerText = "yearly";
                    xe1.AppendChild(xesub3);
                    XmlElement xesub4 = xmlDoc.CreateElement("priority");
                    xesub4.InnerText = "0.8";
                    xe1.AppendChild(xesub4);
                    root.AppendChild(xe1);
                }
                xmlDoc.Save(sitemapFileFullNamePath);    //此处放xml文件的保存地址
                sb.AppendLine("</ol>");
                sb.AppendLine("</body>");
                sb.AppendLine("</html>");
                htmlsw.WriteLine(sb.ToString());
                htmlsw.Flush();
                htmlsw.Close();

                sw.Flush();
                sw.Close();

                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                return Success("ok");
            }
            catch (Exception ex)
            {
                return Error("SiteMapXml生成数据失败：" + ex.Message);
            }
        }
        #endregion


    }

}
